package com.pet.controller.AI.aiUtil;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pet.entity.AI.AiContent;
import com.pet.properties.AiSparkProperties;
import com.pet.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ConnectionUtil {
    @Autowired
    private AiSparkProperties aiSparkProperties;

    //配置对话信息函数
    public Result configDialogueInfo(JSONObject message) {
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            log.info("AiContent:{}",message);
            log.info("AiSparkProperties:{}",aiSparkProperties);
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(aiSparkProperties.getHttpPost());

            // 设置请求头
            httpPost.setHeader("Authorization", aiSparkProperties.getAuthorization());
            httpPost.setHeader("Content-Type", "application/json");

            // 创建JSON请求体
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("model", aiSparkProperties.getModel());
            log.info("问答：{}",message.getString("content"));
            // 设置对话信息messages
            jsonObject.put("messages", java.util.Collections.singletonList(message));
            //jsonObject.put("stream", true);

            // 将JSON对象转换为字符串，并设置为请求体
            StringEntity entity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response Code: " + statusCode);

                // 获取响应体
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                //打印返回的详细数据
                System.out.println("Response Body: " + responseBody);
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode rootNode = objectMapper.readTree(responseBody);
                    // 导航到choices数组，并获取第一个元素的message对象的content字段
                    JsonNode choicesNode = rootNode.get("choices");
                    if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                        JsonNode firstChoiceNode = choicesNode.get(0);
                        JsonNode messageNode = firstChoiceNode.get("message");
                        if (messageNode != null) {
                            JsonNode contentNode = messageNode.get("content");
                            if (contentNode != null) {
                                String content = contentNode.asText();
                                System.out.println("Content: " + content);
                                return Result.success(content);
                            }
                        }
                    }

                    // 如果未找到content，可以返回一个错误或默认值
                    return Result.error("Content not found in response");
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.error("Error parsing JSON response");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }



}